clear all
clc

conn = database('BDC','','');
labels = {0,1,1.5,2,2.5,3,3.5,4,4.5,5,5.5,-1};
numRate = length(labels);
table = 'final_v3_tbl';
year_list=1997:2009;
DURATION = 1;
NUMBER_OF_YEAR = length(year_list) - DURATION;

cohTp = zeros(NUMBER_OF_YEAR, numRate, numRate);
cohTtlVec = zeros(NUMBER_OF_YEAR, 1, numRate);
cohTtlMat = zeros(NUMBER_OF_YEAR, numRate, numRate);
durTp = zeros(NUMBER_OF_YEAR, numRate, numRate);
durTtlVec = zeros(NUMBER_OF_YEAR, 1, numRate);
durTtlMat = zeros(NUMBER_OF_YEAR, numRate, numRate);

for yearIdx=1: NUMBER_OF_YEAR 
    
    Date1 = strcat(num2str(year_list(yearIdx)),'-12-01');
    Date2 = strcat(num2str(year_list(yearIdx+DURATION)),'-12-01');

    sqlquery1 = strcat(['select Customer, modiFisDate, modiRate FROM final_v3_tbl where modiFisDate BETWEEN ''' Date1 ''' and ''' Date2 '''']);
    results = fetch(conn, sqlquery1);
    disp(size(results));
    
    [cohTp(yearIdx,:,:),ttl] = transprob(results, 'labels',labels,'algorithm','cohort');
    cohTtlVec (yearIdx,1,:) = ttl.totalsVec;
    cohTtlMat (yearIdx,:,:) = ttl.totalsMat;    
    
    [durTp(yearIdx,:,:),ttl] = transprob(results, 'labels',labels);
    durTtlVec (yearIdx,1,:) = ttl.totalsVec;
    durTtlMat (yearIdx,:,:) = ttl.totalsMat;  
    
    disp( strcat(['Date: ' Date1 ' to ' Date2]));
end

% To calculate average tranprob
snapsPerYear = 1;
transInterval = 1;

% cohort
avgCohTotalVec(:,:) = sum(cohTtlVec,1);
avgCohTotalMat(:,:) = sum(cohTtlMat,1);
sampleTotals = struct('totalsVec',avgCohTotalVec,'totalsMat',avgCohTotalMat);
avgCohTp = getTransProb(sampleTotals,snapsPerYear,transInterval,'cohort');

% duration
avgDurTotalVec(:,:) = sum(durTtlVec,1);
avgDurTotalMat(:,:) = sum(durTtlMat,1);
sampleTotals = struct('totalsVec',avgDurTotalVec,'totalsMat',avgDurTotalMat);
avgDurTp = getTransProb(sampleTotals,snapsPerYear,transInterval,'duration');


